package com.yuhs.zixing.study.thread.juc.code002;

import lombok.SneakyThrows;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * @description 银行账户模拟操作 对写加锁 读不加锁
 * @author: yuhs
 * @date 2021/11/20 7:57 下午
 */
public class Demo001_BankAccount {
    /**
     * 姓名
     */
    String name;
    /**
     * 余额
     */
    BigDecimal balance;

    @SneakyThrows
    public synchronized void set(String name, BigDecimal balance) {
        this.name = name;
        TimeUnit.SECONDS.sleep(2);
        this.balance = balance;
    }

    public /*synchronized*/ BigDecimal getBalance(String name) {
        return this.balance;
    }

    public static void main(String[] args) throws InterruptedException {
        Demo001_BankAccount bankAccount = new Demo001_BankAccount();
        new Thread(() -> bankAccount.set("张三", new BigDecimal("100.00"))).start();
        TimeUnit.SECONDS.sleep(1);
        System.out.println("张三的余额: " + bankAccount.getBalance("张三"));
        TimeUnit.SECONDS.sleep(2);
        System.out.println("张三的余额: " + bankAccount.getBalance("张三"));
    }
}
